<script setup lang="ts">
import { ref, unref } from 'vue'
import { BasicForm, useForm } from '@/components/Form'
import { formSchema } from '@/views/sys/employee/employee.data'
import { BasicModal, useModalInner } from '@/components/Modal'
import { employeeApi } from '@/api/sys/employeeApi'
import type { EmployeeAddReq, EmployeeUpdateReq } from '@/model/sys/employeeModel'

defineOptions({ name: 'EmployeeModal' })
const emit = defineEmits(['success', 'register'])
const isUpdate = ref(true)

const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
  labelWidth: 120,
  baseColProps: { span: 24 },
  schemas: formSchema,
  showActionButtonGroup: false,
  actionColOptions: { span: 23 },
})

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  await resetFields()
  setModalProps({ confirmLoading: false })
  isUpdate.value = !!data?.isUpdate
  if (unref(isUpdate)) {
    const record = data.record
    const values = await employeeApi.detail(record.employeeId)
    setFieldsValue({ ...values })
  }
})

async function handleSubmit() {
  try {
    const values = await validate()
    setModalProps({ confirmLoading: true })
    if (unref(isUpdate))
      await employeeApi.update(values as EmployeeUpdateReq)
    else await employeeApi.add(values as EmployeeAddReq)

    closeModal()
    emit('success')
  }
  finally {
    setModalProps({ confirmLoading: false })
  }
}
</script>

<template>
  <BasicModal
    v-bind="$attrs"
    :min-height="300"
    :title="isUpdate ? '更新' : '新增'"
    @register="registerModal"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
